<template>
	<view class="container" style="background-color: #1e1e36;">
		<!-- 微信登录 -->
		<view v-if="!userName" class="login-box">
			<button class="button" @click="create">注册</button>
			<button class="button" @tap="navigateToTopScores">查看排行榜</button>
		</view>

		<!-- 用户名获取成功但未开始游戏 -->
		<view v-else-if="userName && !gameStarted" class="start-game-box">
			<text style="color:white;">欢迎, {{ userName }}!</text>
			<button class="button" @tap="startGame">开始游戏</button>
			<button class="button" @tap="navigateToTopScores">查看排行榜</button>
			<button class="button" @tap="queryHighScore">查询我的最高分</button>
			<button class="button" @click="create">变更信息</button>
		</view>

		<!-- 游戏主界面 -->
		<view v-else-if="gameStarted" class="game-container">
			<!-- 倒计时进度条和文本 -->
			<progress :percent="countdownPercent" activeColor="#007AFF" backgroundColor="#555" />
			<text style="color:white;text-align:center;">{{ countdownText }}</text>

			<!-- 游戏结束提示 -->
			<view v-if="gameOver" class="game-over">
				<text class="game-over-text" style="color:white;">游戏结束！你的最终得分：{{ score }}</text>
				<button class="button" @tap="resetGame">重新开始</button>
			</view>

			<!-- 答题界面 -->
			<view v-else>
				<view class="score-board">
					<text style="color:white;">当前分数：{{ score }}</text>
				</view>

				<view class="question-box">
					<text class="question-text">{{ currentQuestion }}</text>
					<view class="options">
						<button v-for="(option, index) in options" :key="index" class="option-button"
							:class="{ selected: selectedAnswer === option }" @tap="selectAnswer(option)"
							style="border-radius: 8px; background-color: white; color:#1e1e36;">
							{{ option }}
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config.js'; // 导入配置文件
	export default {
		data() {
			return {
				userName: '',
				gameStarted: false,
				countdown: 10,
				countdownInterval: null,
				score: 0,
				gameOver: false,
				currentQuestion: '',
				options: [],
				selectedAnswer: null,
				isFirstRequest: true // 新增的变量
			}
		},
		onShow() {
			// 页面显示时自动加载最新用户信息
			this.loadUserInfo();
		},
		methods: {
			loadUserInfo() {
				uni.getStorage({
					key: 'userInfo',
					success: (res) => {
						const {
							avatarUrl,
							nickname
						} = res.data;
						this.userAvatarUrl = avatarUrl || ''; // 如果没有保存的头像，则为空字符串
						this.userName = nickname || ''; // 如果没有保存的昵称，则为空字符串
						console.log('IMG',this.userAvatarUrl);
						console.log('NAME',this.userName);
					},
					fail: () => {
						console.log('未找到已保存的用户信息');
					}
				});
			},
			create() {
				uni.navigateTo({
					url: '/pages/quiz/info/info' // 假设排行榜页面路径为/pages/topScores/topScores
				});
			},
			startGame() {
				if (!this.userName) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				this.gameStarted = true;
				this.score = 0;
				this.startCountdown();
				this.fetchQuestion(); // 假设这是开始游戏时你需要调用的方法
			},
			startCountdown() {
				this.countdown = 10; // 重置倒计时
				if (this.countdownInterval) clearInterval(this.countdownInterval); // 清除旧的定时器
				this.countdownInterval = setInterval(() => {
					if (this.countdown > 0 && !this.gameOver) this.countdown--; // 只有当游戏未结束时才减少倒计时
					else if (this.gameOver) {
						clearInterval(this.countdownInterval);
					} else {
						clearInterval(this.countdownInterval);
						this.selectAnswer('timeout');
					}
				}, 1000);
			},
			async fetchQuestion() {
				try {
					const res = await uni.request({
						url: `${config.BASE_URL}/get_question`,
						method: 'POST',
						data: {
							username: this.userName,
							isFirstRequest: this.isFirstRequest,
							userimg: this.userAvatarUrl
						},
						header: {
							'Content-Type': 'application/json'
						}
					});

					// 打印完整的响应对象以供调试
					console.log('获取题目响应:', res);


					// 判断是否是第一次请求，并添加相应的数据
					if (this.isFirstRequest) {
						this.isFirstRequest = false;
					}

					// 直接从res.data中获取数据
					if (res.data.question === "所有问题都已回答") {
						this.gameOver = true;
						return;
					}

					this.currentQuestion = res.data.question;
					this.options = res.data.options; // 确保选项数组被正确赋值
					this.selectedAnswer = null;

				} catch (error) {
					uni.showToast({
						title: '获取题目失败',
						icon: 'none'
					});
					console.error('请求过程中出现错误:', error);
					if (error.response) {
						console.error('服务器响应:', error.response.data);
						console.error('状态码:', error.response.status);
						console.error('响应头:', error.response.headers);
					} else {
						console.error('请求错误:', error.message);
					}
				}
			},
			resetCountdown() {
				this.countdown = 10;
				if (this.countdownInterval) clearInterval(this.countdownInterval); // 清除旧的定时器
				this.startCountdown();
			},
			async selectAnswer(answer) {
				this.selectedAnswer = answer
				try {
					const res = await uni.request({
						url: `${config.BASE_URL}/submit_answer`,
						method: 'POST',
						data: {
							username: this.userName,
							answer: answer,
							current_question: this.currentQuestion
						},
						header: {
							'Content-Type': 'application/json'
						}
					})

					if (res.data.status === 'wrong') {
						this.gameOver = true
						return
					}

					if (res.data.status === 'completed') {
						this.gameOver = true
						this.score = res.data.score
						return
					}
					this.score = res.data.score
					this.resetCountdown(); // 调用重置倒计时的方
					await this.fetchQuestion()
				} catch (error) {
					uni.showToast({
						title: '提交答案失败',
						icon: 'none'
					})
				}
			},
			resetGame() {
				this.gameStarted = false;
				this.score = 0;
				this.gameOver = false;
				this.currentQuestion = '';
				this.options = [];
				this.isFirstRequest = true;
			},
			navigateToTopScores() {
				uni.navigateTo({
					url: '/pages/quiz/topScores/topScores' // 假设排行榜页面路径为/pages/topScores/topScores
				});
			},
			async queryHighScore() {
				try {
					const res = await uni.request({
						url: `${config.BASE_URL}/query_score/${this.userName}`,
						method: 'GET'
					});
					uni.showToast({
						title: `你的最高分是 ${res.data.score} 分`,
						icon: 'none'
					});
				} catch (error) {
					console.error('查询最高分失败:', error);
					uni.showToast({
						title: '查询最高分失败',
						icon: 'none'
					});
				}
			}
		},
		computed: {
			countdownPercent() {
				return (this.countdown / 10) * 100;
			},
			countdownText() {
				return `剩余时间：${this.countdown}s`;
			}
		}
	}
</script>

<style>
	/* 容器设置为flex，并启用垂直和水平居中 */
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-image: url('https://education-cos-1307366133.cos.ap-shanghai.myqcloud.com/广东省科学技术普及志愿者协会/广东省科学技术普及志愿者协会-学生-311/staitc/match.png');
		background-size: 450px;
		background-position: -20px center;
		/* 水平居中 */
		min-height: 100vh;
		/* 设置最小高度为视窗高度，确保有足够的空间进行垂直居中 */
		box-sizing: border-box;
		justify-content: center;
		color: white;
	}

	.login-box,
	.game-over,
	.question-box {
		width: 100%;
		/* 确保这些容器有足够的宽度并且居中 */
		box-sizing: border-box;
		margin-top: 20px;
		/* 增加顶部间距，使得内容不紧贴顶部 */
		display: flex;
		flex-direction: column;
		align-items: center;
		/* 内部元素水平居中 */
		justify-content: center;
		/* 内部元素垂直居中 */
	}

	.input {
		width: 80%;
		/* 输入框宽度100%，以填充其父容器 */
		height: 40px;
		border: 1px solid #ccc;
		margin-bottom: 20px;
		padding: 0 10px;
		box-sizing: border-box;
		/* 确保padding不会影响输入框的整体宽度 */
	}

	.button {
		width: 80%;
		/* 按钮宽度占父容器的80%，以保持一定的边距 */
		max-width: 300px;
		width: 100%;
		/* 设置按钮的最大宽度，避免过宽 */
		height: 40px;
		background-color: #007AFF;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 20px 0;
		/* 上下外边距为10px */
		box-sizing: border-box;
	}

	.question-text {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20px;
		text-align: center;
		/* 文本居中 */
		width: 100%;
		/* 让文本占据整个容器的宽度 */
	}

	.options {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* 选项垂直排列且居中 */
		width: 100%;
		gap: 10px;
		/* 选项之间的间距 */
	}

	.option-button {
		width: 100%;
		/* 选项按钮宽度100% */
		height: 40px;
		background-color: aquamarine;
		color: aquamarine;
		box-sizing: border-box;
		margin-bottom: 15px;
	}

	.selected {
		background-color: #007AFF;
		color: white;
	}

	.top-scores {
		background-color: white;
		padding: 20px;
		width: 80vw;
		/* 视窗宽度的80% */
		box-sizing: border-box;
		text-align: center;
		/* 文本居中 */
	}

	.title,
	.score-item {
		width: 100%;
		/* 标题和分数项宽度100% */
		box-sizing: border-box;
	}

	/* 添加磨砂背景效果 */
	.game-container {
		padding: 20px;
		border-radius: 15px;
		/* 设置圆角大小 */
		background-color: rgba(30, 30, 54, 0.5);
		/* 半透明白色背景，可根据需要调整透明度 */
		backdrop-filter: blur(10px);
		/* 磨砂效果，模糊半径可根据需要调整 */
		box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
		/* 可选：添加一些阴影增加层次感 */
		width: 90vw;
		/* 或者根据需求设置宽度 */
		margin: auto;
		/* 居中显示 */
	}

	.start-game-box {
		padding: 20px;
		border-radius: 15px;
		/* 设置圆角大小 */
		background-color: rgba(30, 30, 54, 0.5);
		/* 半透明白色背景，可根据需要调整透明度 */
		backdrop-filter: blur(10px);
		/* 磨砂效果，模糊半径可根据需要调整 */
		box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
		/* 可选：添加一些阴影增加层次感 */
		margin: auto;
		/* 居中显示 */
	}
</style>